package com.buobao.jdbc.demo;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * druid连接池示例
 */
public class DruidSample {
    public static void main(String[] args) {
        //1.加载属性文件
        Properties properties = new Properties();
        String propertiesPath = DruidSample.class.getResource("./druid-config.properties").getPath(); //获取配置文件路径
        try {
            propertiesPath = URLDecoder.decode(propertiesPath,"UTF-8"); //处理路径编码等问题，如中文空格等
            properties.load(new FileInputStream(propertiesPath)); //加载配置文件
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //2.获取DataSource数据源对象
        Connection connection=null;
        try {
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            connection = dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //3.使用connection查询,和jdbc一致
        PreparedStatement statement=null;
        ResultSet resultSet = null;
        if (connection!=null) {
            try {
                statement = connection.prepareStatement("select * from employee limit 1,10");
                resultSet = statement.executeQuery();
                while(resultSet.next()) {
                    System.out.println(resultSet.getInt("eno"));
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    DbUtil.closeConnection(resultSet,statement,connection);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
